package com.yuyou.fn.educational.service.impl;

import cn.beststudy.member.*;
import com.alibaba.fastjson.JSONObject;
import com.github.wens.mybatisplus.toolkit.StringUtil;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.service.ISiteConfigService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Urls;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.Student;
import com.yuyou.fn.educational.service.IMemberStudentService;
import com.yuyou.fn.educational.service.IStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MemberStudentServiceImpl implements IMemberStudentService {

    static Map<Integer,Integer> sexMap=new HashMap<>();
    static {
        sexMap.put(1,1);
        sexMap.put(2,0);
    }

    private volatile RegistrationServiceSoap registrationService ;


    @Resource
    private ISiteConfigService siteConfigService;

    private final Logger log = LoggerFactory.getLogger(MemberStudentServiceImpl.class);
    private RegistrationServiceSoap getRegistrationService() {


        synchronized (this){
            if(registrationService != null ){
                return registrationService ;
            }
            registrationService =  new RegistrationService(Urls.create(siteConfigService.getConfigValueFromCache("member_webservice_url"))).getRegistrationServiceSoap();
        }
        return registrationService;
    }


    @Override
    public String changeOrNewStudentNew(Student student) {
        try{
            return getRegistrationService().changeOrNewStudentNew(this.toSrcAllClientTMSByStudent(student));
        }catch (Exception e){
            log.error("插入或者更新会员库失败: {} " , JSONObject.toJSONString(student));
            throw new BusException("学生id:"+student.getStudentId()+",插入或者更新会员库失败" , e );
        }
    }

    @Override
    public Student selectByMemberIDNew(String cid) {
        try{
            MemberProfileNewDTO memberProfileNewDTO = getRegistrationService().selectByMemberIDNew(cid);
            if (memberProfileNewDTO==null){
                throw new BusException("查不到该学生");
            }
            return this.toStudentByMember(memberProfileNewDTO);

        }catch (Exception e){
            log.error("根据cid查询会员库学生失败，cid: {}, exception{}" ,cid,e);
        }
        return null;
    }

    private Student toStudentByMember(MemberProfileNewDTO memberProfileNewDTO){
        Student student=new Student();
        student.setPhoneNo(memberProfileNewDTO.getMainPhoneNum());
        student.setName(memberProfileNewDTO.getFullName());
        if (StringUtil.isNotEmpty(memberProfileNewDTO.getBirthday())){
            student.setBirthday(Utils.parseDate(memberProfileNewDTO.getBirthday(),"yyyy-MM-dd"));
        }
        student.setSchool(memberProfileNewDTO.getSourceSchool());
        student.setSlavePhoneNo(memberProfileNewDTO.getSlavePhoneNum());
        return student;
    }

    private SrcAllClientTMS toSrcAllClientTMSByStudent(Student student){
        SrcAllClientTMS srcAllClientTMS=new SrcAllClientTMS();
        //srcAllClientTMS.setID(student.getCid());
        srcAllClientTMS.setClientID(student.getCid());
        srcAllClientTMS.setFullName(student.getName());
        srcAllClientTMS.setClientSourceTypeID((short)22);//誉优22
        srcAllClientTMS.setClientRoleTypeID((short) 1);//客户身份1-学生；2-家长；3-教师
        short sex=sexMap.get(student.getSex())==null?(short) 2:sexMap.get(student.getSex()).shortValue();
        srcAllClientTMS.setSexFlag(sex);  //0-女性；1-男性；2-未填
        srcAllClientTMS.setBizClientID(student.getStudentId().toString());
        srcAllClientTMS.setBizClientCode(student.getStudentNo());

        srcAllClientTMS.setBirthday(student.getBirthday()==null?"1970-01-01":Utils.formatDate(student.getBirthday(),"yyyy-MM-dd"));
        srcAllClientTMS.setSourceSchool(student.getSchool());
        srcAllClientTMS.setSignUpCityName("");
        srcAllClientTMS.setSignUpGradeName(student.getGradeName());
        srcAllClientTMS.setSignUpSchoolName(student.getLastRegCampusName());
        srcAllClientTMS.setMainPhoneNum(student.getPhoneNo());
        srcAllClientTMS.setSlavePhoneNum(student.getSlavePhoneNo());
        srcAllClientTMS.setThirdPhoneNum("");
        srcAllClientTMS.setDeletedFlag(false);
        srcAllClientTMS.setStatus((short) 2);
        srcAllClientTMS.setClientRegDate(TimeUtils.dateToXmlDate(student.getCreateTime()));
        srcAllClientTMS.setCreateDate(TimeUtils.dateToXmlDate(student.getCreateTime()));
        srcAllClientTMS.setModifiedDate(TimeUtils.dateToXmlDate(student.getUpdateTime()));
        return srcAllClientTMS;
    }

    @Override
    public List<MemberIDChangeDTO> getSyncMemberIDChange(Date startDate) {
        String time=Utils.formatDate(startDate,"yyyy-MM-dd HH:mm:ss");
        PageResult2DTO pageResult2DTO = getRegistrationService().getSyncMemberIDChange(time,50000,1);
        ArrayOfMemberIDChangeDTO data = pageResult2DTO.getData();
        List<MemberIDChangeDTO> memberIDChangeDTOList = data.getMemberIDChangeDTO();
        return memberIDChangeDTOList;
    }
}
